﻿using Entity.PointsActivety;
using Logics;

namespace Services.PointsActivity;


/// <summary>
/// 排队免单客户端接口
/// </summary>
[Authorize, ApiDescriptionSettings("排队免单")]
public class PointsActivityServices : BaseServices
{
    private readonly ISqlSugarClient db;

    private readonly Glod glod;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="db"></param>
    /// <param name="glod"></param>
    public PointsActivityServices(ISqlSugarClient db, Logics.Glod glod)
    {
        this.db = db;
        this.glod = glod;
    }

    /// <summary>
    /// 创建排队免单订单
    /// </summary>
    /// <param name="price">支付金额</param>
    /// <param name="storeId">所属商户</param>
    /// <returns></returns>
    public async Task<object> Created(decimal price, int storeId)
    {
        //商户信息
        var store = await db.Queryable<Entity.Store>().FirstAsync(x => x.Id == storeId);

        //排队活动信息
        var active = await db.Queryable<Entity.PointsActivety.PointsActivity>()

            .FirstAsync(x => x.StoreId == storeId && x.Status == Entity.PointsActivety.PointsActivityStatus.进行中);

        //活动是否存在
        if (active == null) return No("商户未开通排队免单活动");

        //活动状态检测
        if (active.Status == PointsActivityStatus.已结束) return No("活动已结束");

        //排队金额 加入奖池得金额
        decimal activePrice = price * (1 - active.Radio);

        //商户所得金额
        decimal storePrice = price;

        //用户排队最终所得金额
        decimal userPrice = price;


        //订单编号
        string orderNo = Extends.GetOrderNo();



        //订单数据
        var order = new Entity.Order
        {
            OldPrice = price,

            PayPrice = price,

            OrderNo = orderNo,

            OrderType = Entity.OrderType.排队免单,

            StoreId = storeId,

            UserId = USERID,

            ProxyId = store.ProxyId,
        };

        try
        {
            db.Ado.BeginTran();

            //录入订单数据
            int orderId = await db.Insertable(order).ExecuteReturnIdentityAsync();

            //录入订单扩展数据
            var orderExt = new Entity.Orders.Order_Out_PintsActivity
            {
                OrderId = orderId,

                OrderNo = orderNo,

                ActiveId = active.Id,

                ActivePrice = activePrice,

                UserPrice = userPrice,

                StorePrice = storePrice
            };

            await db.Insertable(orderExt).ExecuteReturnIdentityAsync();

            db.Ado.CommitTran();

            return Ok(orderNo);
        }
        catch (Exception e)
        {
            db.Ado.RollbackTran();

            Console.WriteLine(e.Message);

            return No("下单失败");
        }

    }

    /// <summary>
    /// 排队免单出队
    /// </summary>
    /// <returns></returns>
    public async Task<object> Out(int id)
    {
        var active = await db.Queryable<Entity.PointsActivety.PointsActivityQueue>().FirstAsync(x => x.Id == id && x.ClientId == USERID);

        if (active == null) return No("未找到排队免单数据");

        if (active.State != ActiveState.进行中) return No("无法退出排队");

        try
        {
            db.Ado.BeginTran();

            //更新剩下用户的排队序号
            bool state = await db.Updateable<PointsActivityQueue>().Where(x => x.ActiveId == active.ActiveId && x.Index > active.Index).SetColumns(x => x.Index == x.Index - 1).ExecuteCommandHasChangeAsync();

            active.State = ActiveState.已退出;

            active.OutNotes = "用户主动退出";

            state = await db.Updateable(active).ExecuteCommandHasChangeAsync();

            await glod.Add(USERID, active.StoreId, active.Price / 2, "退出排队,金币兑换到账!");

            db.Ado.CommitTran();

            return Msg(state);
        }
        catch (Exception)
        {
            db.Ado.RollbackTran();

            return No("操作失败");
        }


    }

    /// <summary>
    /// 获取活动列表
    /// </summary>
    /// <param name="state">-1全部</param>
    /// <returns></returns>
    public async Task<object> Get(int state)
    {
        var list = await db.Queryable<PointsActivityQueue>().Where(x => x.ClientId == USERID)

            .Includes(x => x.Active)

            .Includes(x => x.Store)

            .WhereIF(state > -1, x => x.State == (ActiveState)state)

            .OrderBy(x => x.ActiveId, OrderByType.Desc)

            .WithCache(5)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(list);
    }

    /// <summary>
    /// 获取活动详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<object> GetDetail(int id)
    {
        int myIndex = await db.Queryable<PointsActivityQueue>().Where(x => x.ClientId == USERID && x.ActiveId == id).Select(x => x.Index).FirstAsync();

        var activeUser = await db.Queryable<PointsActivityQueue>()

            .Where(x => x.Index >= myIndex)

            .Where(x => x.ActiveId == id)

            .Where(x => x.State == ActiveState.进行中)

            .Includes(x => x.Client)

            .ToPagedListAsync(PageNo, PageSize);

        var active = await db.Queryable<Entity.PointsActivety.PointsActivity>().FirstAsync(x => x.Id == id);

        return Ok(new
        {
            users = activeUser,

            active
        });
    }

    /// <summary>
    /// 获取详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<object> GetActiveDetail(int id)
    {
        var data = await db.Queryable<Entity.PointsActivety.PointsActivityQueue>()

            .Includes(x => x.Client)

            .Includes(x => x.Active)

            .Includes(x => x.Store)

            .FirstAsync(x => x.Id == id);

        return Ok(data);
    }

    /// <summary>
    /// 获取排队免单核销二维码
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetResolveQrimg(int queueId)
    {
        var data = await db.Queryable<Entity.PointsActivety.PointsActivityQueue>()

            .Includes(x => x.Active)

            .Includes(x => x.Store)

            .FirstAsync(x => x.Id == queueId && x.ClientId == USERID);

        if (data == null) return No("无领奖信息");

        if (data.State != ActiveState.可领奖) return No("您还未达到领奖条件");

        return Ok(new
        {
            url = $"https://teambuystore.shuangdian.vip/#/pages/resolve?id={queueId}",

            info = data
        });
    }


}

